package com.atguigu.distributed.lock.leecode.dinamic;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class LogManager {
    private static final LogManager INSTANCE = new LogManager();

    private List<String> logCache; // 存储日志的缓存列表
    private int maxCacheSize; // 缓存列表的最大容量
    private long uploadInterval; // 上传间隔时间
    private int uploadThreshold; // 触发上传的日志数量阈值

    private LogManager() {
        this.logCache = new ArrayList<>();
        this.maxCacheSize = 1000; // 设置默认缓存大小为1000
        this.uploadInterval = 60; // 设置默认上传间隔为60秒
        this.uploadThreshold = 100; // 设置默认上传阈值为100条

        // 定时任务，每隔uploadInterval时间上传日志
        Timer timer = new Timer();
        timer.schedule(new UploadTask(), this.uploadInterval * 1000, this.uploadInterval * 1000);
    }

    public static LogManager getInstance() {
        return INSTANCE;
    }

    public synchronized void log(String message) {
        logCache.add(message);
        if (logCache.size() >= maxCacheSize) {
            uploadLogs(); // 缓存满时立即上传
        } else if (logCache.size() >= uploadThreshold) {
            uploadLogs(); // 达到上传阈值时上传
        }
    }

    private synchronized void uploadLogs() {
        // 模拟上传日志的动作
        System.out.println("Uploading logs...");
        for (String log : logCache) {
            System.out.println(log);
        }
        logCache.clear(); // 清空缓存
    }

    // 内部类，用于执行上传任务
    private class UploadTask extends TimerTask {
        @Override
        public void run() {
            uploadLogs(); // 执行上传任务
        }
    }

    public static void main(String[] args) {
        // 示例用法
        LogManager logger = LogManager.getInstance();
        logger.log("Error log 1");
        logger.log("Error log 2");
        logger.log("Error log 3");
        logger.log("Error log 4");
        logger.log("Error log 5");
    }
}
